package solvers.linearsupport;

import globals.CentralStatics;

import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.DecompositionSolver;
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import org.apache.commons.math3.linear.SingularMatrixException;

public class LinearFunction {

	public double[] abcVector;
	
	
	public LinearFunction(){
		this.abcVector=null;
	}
	
	public LinearFunction(double[][] xMatrix, double[] yVector){
		this.inferFromPoints(xMatrix, yVector);
	}
	
	public boolean inferFromPoints(double[][] xMatrix, double[] yVector){
		
		try{
			RealMatrix coefficients = new Array2DRowRealMatrix(xMatrix,false);
			//coefficients.transpose();
			//if(++classCNT==3){
			DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();			          
			RealVector constants = new ArrayRealVector(yVector, false);
			RealVector solution = solver.solve(constants);
			abcVector=solution.toArray();
			return true;
		} catch(SingularMatrixException sme){
			//System.err.println("AAARG: "+sme.getMessage());
			//System.err.println(MathHelpers.matrixEquation2String(xMatrix, yVector));
			return false;
		}
	}
	
	public double valueAt(double[] inputVars){
		return CentralStatics.innerProduct(inputVars, this.abcVector);
	}
}
